<template>
  <div class="order-pay-page">
    <div v-if="loading && !orderDetail && !payInfo" class="loading-state">
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 支付记录查看模式 -->
    <div v-else-if="payInfo" class="pay-info-view">
      <nut-cell-group :title="'支付信息'">
        <nut-cell title="支付流水号" :desc="payInfo.payNo || '--'" />
        <nut-cell title="订单ID" :desc="payInfo.orderId || '--'" />
        <nut-cell title="订单总金额" :desc="formatAmount(payInfo.totalAmount)" />
        <nut-cell title="已支付金额" :desc="formatAmount(payInfo.paidAmount)" />
        <nut-cell title="未支付金额" :desc="formatAmount(payInfo.unpaidAmount)" />
        <nut-cell title="优惠金额" :desc="formatAmount(payInfo.discountAmount)" />
        <nut-cell title="支付类型" :desc="payInfo.payTypeName || '--'" />
        <nut-cell title="支付方式" :desc="payInfo.payMethodName || '--'" />
        <nut-cell title="支付渠道" :desc="payInfo.payChannelName || '--'" />
        <nut-cell title="支付状态">
          <template #desc>
            <nut-tag :type="getPayStatusTagType(payInfo.payStatus)">{{ payInfo.payStatusName || '--' }}</nut-tag>
          </template>
        </nut-cell>
        <nut-cell title="支付时间" :desc="formatTime(payInfo.paidTime)" />
        <nut-cell title="取消时间" :desc="formatTime(payInfo.cancelTime)" />
      </nut-cell-group>

      <div v-if="canCancelPay" class="action-buttons">
        <nut-button type="primary" block @click="handlePay">支付</nut-button>
      </div>
    </div>

    <!-- 创建支付模式 -->
    <div v-else-if="orderDetail" class="pay-create-view">
      <nut-form ref="formRef" :model-value="formData" :rules="rules">
        <!-- 订单信息 -->
        <nut-cell-group title="订单信息">
          <nut-cell title="订单编号" :desc="orderDetail.orderNo || '--'" />
          <nut-cell title="订单总金额" :desc="formatAmount(orderDetail.totalAmount)" />
          <nut-cell title="已支付金额" :desc="formatAmount(orderDetail.paidAmount)" />
          <nut-cell title="未支付金额" :desc="formatAmount(orderDetail.unpaidAmount)" />
        </nut-cell-group>

        <!-- 支付信息 -->
        <nut-cell-group title="支付信息">
          <nut-form-item label="支付渠道" required prop="payChannel" :rules="[{ required: true, message: '请选择支付渠道' }]">
            <nut-radio-group v-model="formData.payChannel" direction="horizontal">
              <nut-radio v-for="item in payChannelOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
                {{ item.dictLabel }}
              </nut-radio>
            </nut-radio-group>
          </nut-form-item>

          <nut-form-item v-if="formData.payChannel === '01'" label="支付方式" prop="payMethod">
            <nut-radio-group v-model="formData.payMethod" direction="horizontal">
              <nut-radio v-for="item in payMethodOfflineOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
                {{ item.dictLabel }}
              </nut-radio>
            </nut-radio-group>
          </nut-form-item>

          <nut-form-item label="支付金额" required prop="paidAmount" :rules="amountRules">
            <nut-input v-model="formData.paidAmount" placeholder="请输入支付金额" type="number" clearable />
            <div class="amount-hint">
              <span>可支付金额: {{ formatAmount(orderDetail.unpaidAmount) }}</span>
            </div>
          </nut-form-item>
        </nut-cell-group>

        <!-- 提交按钮 -->
        <div class="action-buttons">
          <nut-button type="primary" block :loading="submitting" @click="handleSubmit">支付</nut-button>
        </div>
      </nut-form>
    </div>

    <div v-else class="empty-state">
      <nut-empty description="订单不存在" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showDialog } from '@nutui/nutui';
  import { useEnumStore } from '@/store/modules/enum';
  import {
    fetchOrderDetail,
    fetchPayInfo,
    createLeftAmountOrder,
    cancelPay,
    type OrderDetail,
    type OrderPayInfo,
    type CreateLeftAmountOrderPayload,
  } from '@/api/order';
  import dayjs from 'dayjs';

  const router = useRouter();
  const route = useRoute();
  const enumStore = useEnumStore();
  // 枚举选项
  const idTypeOptions = computed(() => enumStore.getEnumByType('id_type'));
  const payChannelOptions = computed(() => enumStore.getEnumByType('sp_order_pay_channel'));
  const payMethodOfflineOptions = computed(() => enumStore.getEnumByType('sp_order_offline_pay_method'));
  const payTypeOptions = computed(() => enumStore.getEnumByType('sp_order_pay_type'));

  const formRef = ref<any>(null);
  const submitting = ref(false);
  const loading = ref(false);

  const orderDetail = ref<OrderDetail | null>(null);
  const payInfo = ref<OrderPayInfo | null>(null);

  // 表单数据
  const formData = reactive<CreateLeftAmountOrderPayload>({
    orderId: '',
    payChannel: '00',
    payMethod: undefined,
    paidAmount: 0,
  });

  // 表单验证规则
  const amountRules = [
    { required: true, message: '请输入支付金额' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额' },
  ];

  const rules = {
    payChannel: [{ required: true, message: '请选择支付渠道' }],
    paidAmount: amountRules,
  };

  // 计算属性
  const canCancelPay = computed(() => {
    return payInfo.value?.payStatus === '00';
  });

  // 监听支付渠道变化，线上支付时清空支付方式
  watch(
    () => formData.payChannel,
    (newChannel) => {
      if (newChannel === '00') {
        formData.payMethod = undefined;
      }
    },
  );

  // 加载订单详情
  const loadOrderDetail = async () => {
    const orderId = route.query.orderId as string;
    if (!orderId) {
      showToast.text('订单ID不能为空');
      router.back();
      return;
    }

    try {
      loading.value = true;
      const { code, data, msg }: any = await fetchOrderDetail(orderId);
      if (code !== 200) {
        showToast.text(msg || '获取订单详情失败');
        return;
      }
      const detail = data as OrderDetail;
      orderDetail.value = detail || null;
      formData.orderId = orderId;
      // 默认支付金额为未支付金额
      formData.paidAmount = detail?.unpaidAmount || 0;
    } catch (error: any) {
      console.error('获取订单详情失败', error);
      showToast.text(error?.msg || '获取订单详情失败');
    } finally {
      loading.value = false;
    }
  };

  // 加载支付信息
  const loadPayInfo = async () => {
    const payId = route.query.payId as string;
    if (!payId) {
      showToast.text('支付ID不能为空');
      router.back();
      return;
    }

    try {
      loading.value = true;
      const { code, data, msg }: any = await fetchPayInfo(payId);
      if (code !== 200) {
        showToast.text(msg || '获取支付信息失败');
        return;
      }
      const info = data as OrderPayInfo;
      payInfo.value = info;
    } catch (error: any) {
      console.error('获取支付信息失败', error);
      showToast.text(error?.message || '获取支付信息失败');
    } finally {
      loading.value = false;
    }
  };

  // 格式化时间
  const formatTime = (time?: string) => {
    if (!time) return '--';
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
  };

  // 格式化金额
  const formatAmount = (amount?: number) => {
    if (amount === undefined || amount === null) return '--';
    return `¥${amount.toFixed(2)}`;
  };

  // 获取支付状态标签类型
  const getPayStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'warning';
      case '01':
        return 'success';
      case '02':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 提交支付
  const handleSubmit = () => {
    formRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }

      if (!orderDetail.value) {
        showToast.text('订单信息不存在');
        return;
      }

      const paidAmount = Number(formData.paidAmount);
      const unpaidAmount = orderDetail.value.unpaidAmount || 0;

      if (paidAmount <= 0) {
        showToast.text('支付金额必须大于0');
        return;
      }

      if (paidAmount > unpaidAmount) {
        showToast.text('支付金额不能超过未支付金额');
        return;
      }

      try {
        submitting.value = true;

        const payload: CreateLeftAmountOrderPayload = {
          orderId: formData.orderId,
          payChannel: formData.payChannel,
          paidAmount: paidAmount,
        };

        // 只有线下支付需要传递支付方式
        if (formData.payChannel === '01' && formData.payMethod) {
          payload.payMethod = formData.payMethod;
        }

        const { code, msg }: any = await createLeftAmountOrder(payload);
        if (code !== 200) throw new Error(msg);
        // 线下支付：显示提示弹窗，确认后跳转到订单列表
        if (formData.payChannel === '01') {
          showDialog({
            title: '提示',
            content: '线下支付，等待财务确认',
            onOk: () => {
              router.push({
                path: '/order',
                replace: true,
              });
            },
          });
        } else {
          // 线上支付：跳转到线上支付页面
          if (msg) {
            router.push({
              path: '/order/online-pay',
              query: { payId: msg },
            });
          } else {
            showToast.text('创建支付成功，但未获取到支付ID');
          }
        }
      } catch (error: any) {
        console.error('创建支付失败', error);
        showToast.text(error?.message || '创建支付失败');
      } finally {
        submitting.value = false;
      }
    });
  };

  // 处理支付
  const handlePay = () => {
    if (!payInfo.value?.payId) {
      showToast.text('支付ID不存在');
      return;
    }

    const payChannel = payInfo.value.payChannel;

    // 线上支付：跳转到线上支付页面
    if (payChannel === '00') {
      router.push({
        path: '/order/online-pay',
        query: { payId: payInfo.value.payId },
      });
    } else if (payChannel === '01') {
      // 线下支付：显示提示信息
      showDialog({
        title: '提示',
        content: '线下支付，等待财务确认',
        onOk: () => {
          router.push({
            path: '/order',
            replace: true,
          });
        },
      });
    } else {
      showToast.text('支付渠道信息异常');
    }
  };

  // 取消支付
  const handleCancelPay = () => {
    if (!payInfo.value?.payId) {
      showToast.text('支付ID不存在');
      return;
    }

    showDialog({
      title: '提示',
      content: '确定要取消该支付吗？',
      onOk: async () => {
        try {
          await cancelPay({ payId: payInfo.value!.payId! });
          showToast.text('取消成功');
          loadPayInfo();
        } catch (error: any) {
          console.error('取消支付失败', error);
          showToast.text(error?.message || '取消支付失败');
        }
      },
    });
  };

  // 初始化
  onMounted(() => {
    const payId = route.query.payId as string;
    const orderId = route.query.orderId as string;

    if (payId) {
      // 查看支付记录
      loadPayInfo();
    } else if (orderId) {
      // 创建支付
      loadOrderDetail();
    } else {
      showToast.text('参数错误');
      router.back();
    }
  });
</script>

<style lang="scss" scoped>
  .order-pay-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
  }

  .loading-state {
    padding: 100px 20px;
    text-align: center;

    .loading-text {
      font-size: 28px;
      color: #666;
    }
  }

  .pay-info-view,
  .pay-create-view {
    .amount-hint {
      margin-top: 10px;
      font-size: 24px;
      color: #666;
    }

    .action-buttons {
      padding: 20px;
      margin-top: 20px;
    }
  }

  .empty-state {
    padding: 100px 20px;
    text-align: center;
  }
</style>
